package bblgw

import (
	"code.google.com/p/go-uuid/uuid"
	"hash/crc32"
	"logger"
	"math/rand"
	"time"
)

var log *logger.Logger

func UUID() string {
	return uuid.NewUUID().String()
}

func Rand() int {
	r := rand.New(rand.NewSource(time.Now().UnixNano()))
	return r.Intn(100000000)
}

// func Hash(data []byte) uint32 {
// 	return crc32.ChecksumIEEE(data)
// }
func Hash(key string) uint32 {
	if len(key) < 64 {
		var scratch [64]byte
		copy(scratch[:], key)
		return crc32.ChecksumIEEE(scratch[:len(key)])
	}
	return crc32.ChecksumIEEE([]byte(key))
}

func Timestamp() uint64 {
	return uint64(time.Now().Unix())
}

func Sleep(millisecond int) {
	time.Sleep(time.Duration(millisecond) * time.Millisecond)
}

func Start(conf string) (err error) {
	if err = init_config(conf); err != nil {
		return err
	}
	if err = init_log(); err != nil {
		return err
	}
	if err = init_gateway_server(); err != nil {
		server = nil
		return err
	}
	go server.Serve()
	return nil
}

func Stop() {
	if server != nil {
		server.Stop()
		server = nil
	}
}

func init_log() error {
	logg, err := logger.NewLogger(gw_conf.LogFile, "[gateway] ", gw_conf.LogLevel)
	if err != nil {
		return err
	}
	log = logg
	return nil
}

var server *GatewayServer

func init_gateway_server() error {
	server = &GatewayServer{
		Listen:     gw_conf.Listen,
		Slaves:     gw_conf.Slaves,
		Master:     gw_conf.Master,
		Cachedir:   gw_conf.Cachedir,
		Passphrase: gw_conf.Passphrase,
		UnixSock:   gw_conf.UnixSock,
	}
	return server.Init()
}
